<?php
/**
 *
 * MyPdo.class.php
 * User: kalvin
 * Date: 2018/1/6
 * Time: 上午11:08
 */

namespace Core;


class MyPdo
{
    public static $dbconfig;
    protected $type;
    protected $host;
    private $pdo;
    private $operation;
    public static $obj;

    private function __construct()
    {
        self::$dbconfig = include CONF_DIR . 'Database.php';
        $this->type = $type = self::$dbconfig['type'];
        $this->host = $host = self::$dbconfig['host'];
        $this->dbname = self::$dbconfig['dbname'];
        $this->charset = self::$dbconfig['charset'];
        $this->username = self::$dbconfig['username'];
        $this->password = self::$dbconfig['password'];

        //连接数据库
        $dsn = "$this->type:host=$this->host;dbname=$this->dbname;charset=$this->charset;";
        $this->pdo = new \PDO($dsn, $this->username, $this->password);
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        return $this->pdo;
    }

    public function where($field, $operator, $val)
    {
        if (empty($field) or empty($operator) or empty($val)) {
            echo '值不能为空！';
            return false;
        }
        $this->operation = " $field $operator $val ";
        return $this;
    }

    public function myExec($sql)
    {
        try {
            $res = $this->pdo->exec($sql);
            return $res;
        } catch (\PDOException $e) {
            $this->PringError($sql, $e);
            return false;
        }

    }

    public function find($tableName)
    {
        $sql = "select * from $tableName WHERE $this->operation";
        return $this->getOne($sql);
    }

    public function getAll($sql)
    {
        $res = $this->myQuery($sql);
        return $res->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function getOne($sql)
    {
        $res = $this->myQuery($sql);
        return $res->fetch(\PDO::FETCH_ASSOC);
    }

    public function myQuery($sql)
    {

        try {

            $res = $this->pdo->query($sql);
            return $res;
        } catch (\PDOException $e) {
            $this->PringError($sql, $e);
            return false;
        }

    }

    public static function getInstanec()
    {
        if (!isset(self::$obj)) {
            self::$obj = new self();
            return self::$obj;
        } else {
            return self::$obj;
        }
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    /**
     * @param $sql
     * @param $e
     */
    private function PringError($sql, $e)
    {
        echo '错误信息为：' . $e->getMessage() . '<br/>';
        echo '错误语句为：' . $sql . '<br/>';
        echo '错误代码为：' . $e->getCode() . '<br/>';
    }

}